package com.ccteam.fluidmusic.ui.search

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import com.ccteam.fluidmusic.databinding.FragmentSearchResultPlaylistBinding
import com.ccteam.fluidmusic.ui.playlist.PlaylistSheetDetailFragmentDirections
import com.ccteam.fluidmusic.view.adapters.PlaylistSheetItemCallback
import com.ccteam.fluidmusic.view.adapters.PlaylistSheetSmallPagingAdapter
import com.ccteam.fluidmusic.view.adapters.paging.CustomLoadStateAdapter
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment.Companion.RESULT_MOMENTS_TYPE_KEY
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_PLAYLIST
import com.ccteam.shared.result.moment.MomentListItem
import com.ccteam.shared.result.playlistsheet.PlaylistSheetListItem
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/3/16
 */
@AndroidEntryPoint
class SearchPlaylistResultFragment: Fragment() {

    private var _binding: FragmentSearchResultPlaylistBinding? = null
    private val binding: FragmentSearchResultPlaylistBinding get() = _binding!!

    private val homeSearchPlaylistSheetResultViewModel by viewModels<HomeSearchPlaylistSheetResultViewModel>()


    companion object {
        @JvmStatic
        fun newInstance(searchKey: String,type: Int): SearchPlaylistResultFragment {
            return SearchPlaylistResultFragment().apply {
                arguments = Bundle().apply {
                    putString(SEARCH_KEY, searchKey)
                    putInt("type", type)
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentSearchResultPlaylistBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        val dataAdapter = PlaylistSheetSmallPagingAdapter(callback)
        binding.rvPlaylistSheetList.adapter = dataAdapter.withLoadStateFooter(
            CustomLoadStateAdapter(dataAdapter,true){
                dataAdapter.retry()
            }
        )

        viewLifecycleOwner.lifecycleScope.launch {
            homeSearchPlaylistSheetResultViewModel.playlistSheetList.collectLatest {
                dataAdapter.submitData(it)
            }
        }

        viewLifecycleOwner.lifecycleScope.launch {
            dataAdapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && dataAdapter.itemCount < 1)
            }
        }

        binding.statusView.setRetryClickListener {
            dataAdapter.refresh()
        }
    }

    private val callback = object: PlaylistSheetItemCallback{
        override fun playlistItemClicked(view: View,item: PlaylistSheetListItem) {
            if(homeSearchPlaylistSheetResultViewModel.type == AddOnlineMediaFragment.TYPE_SEARCH){
                findNavController().navigate(
                    PlaylistSheetDetailFragmentDirections
                    .actionGlobalPlaylistSheetDetailFragment(item.id))
            } else {
                parentFragment?.setFragmentResult(RESULT_MOMENTS_TYPE_KEY, bundleOf(
                    RESULT_MOMENTS_TYPE_KEY to MomentListItem.MomentShareItem(
                        item.id, MOMENT_SHARE_TYPE_PLAYLIST,item.title
                        ,"",item.imgUrl
                    )))
                findNavController().navigateUp()
            }

        }

    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}